#include "lvgl.h"
#include <i2cdev.h>
#include "aht.h"
#include "esp_log.h"

// 用来扫描i2c设备，并显示在屏幕上

static lv_obj_t *btn;
static lv_obj_t *btn_aht;
static lv_obj_t *info;
static lv_obj_t *info_aht;
aht_t dev_aht = {0};

static const char *TAG = "aht-example";

void aht10_init()
{
    dev_aht.mode = AHT_MODE_NORMAL;
    dev_aht.type = AHT_TYPE_AHT1x;

    ESP_ERROR_CHECK(aht_init_desc(&dev_aht, 0x38, 0, 1, 2));
    ESP_ERROR_CHECK(aht_init(&dev_aht));

    bool calibrated;
    ESP_ERROR_CHECK(aht_get_status(&dev_aht, NULL, &calibrated));
    if (calibrated)
        ESP_LOGI(TAG, "Sensor calibrated");
    else
        ESP_LOGW(TAG, "Sensor not calibrated!");
}

static void btn_ath_cb(lv_event_t *e)
{
    float temperature, humidity;
    esp_err_t res = aht_get_data(&dev_aht, &temperature, &humidity);
    if (res == ESP_OK)
    {
        lv_label_set_text_fmt(info_aht, "Tem: %.1f°C, Hum: %.2f%%", temperature, humidity);
        ESP_LOGI(TAG, "Temperature: %.1f°C, Humidity: %.2f%%", temperature, humidity);
    }
    else
    {
        ESP_LOGE(TAG, "Error reading data: %d (%s)", res, esp_err_to_name(res));
    }
}

// 使用3500中文字库
//  LV_FONT_DECLARE(myfontchinese);

static void btn_cb(lv_event_t *e)
{
    i2c_dev_t dev = {0};
    dev.cfg.sda_io_num = 1;
    dev.cfg.scl_io_num = 2;
#if HELPER_TARGET_IS_ESP32
    dev.cfg.master.clk_speed = 100000; // 100kHz
#endif
    char info_temp[20] = {0};
    esp_err_t res;
    printf("     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f\n");
    printf("00:         ");
    for (uint8_t addr = 3; addr < 0x78; addr++)
    {
        if (addr % 16 == 0)
        {
            printf("\n%.2x:", addr);
        }
        dev.addr = addr;
        res = i2c_dev_probe(&dev, I2C_DEV_WRITE);

        if (res == 0)
        {
            sprintf(info_temp, "add:%.2x", addr);
            printf(" %.2x", addr);
        }
        else
        {
            printf(" --");
        }
    }
    printf("\n\n");
    lv_label_set_text(info, info_temp);
    // lv_label_set_text_fmt(lbl,"已经按下%d次",count);
}

void lvgl_i2cdev_scan(lv_disp_t *disp)
{
    // 初始化i2c
    i2cdev_init();
    aht10_init();

    lv_obj_t *scr = lv_disp_get_scr_act(disp);

    info = lv_label_create(scr);
    lv_obj_set_pos(info, 5, 5);
    lv_label_set_text(info, "no device");

    info_aht = lv_label_create(scr);
    lv_obj_set_pos(info_aht, 100, 5);
    lv_label_set_text(info_aht, "no data");

    btn = lv_btn_create(scr);
    lv_obj_t *lbl = lv_label_create(btn);
    // lv_obj_set_style_text_font(lbl, &myfontchinese, 0);
    lv_label_set_text(lbl, "scan");
    lv_obj_align(btn, LV_ALIGN_CENTER, -50, 30);

    btn_aht = lv_btn_create(scr);
    lbl = lv_label_create(btn_aht);
    // lv_obj_set_style_text_font(lbl, &myfontchinese, 0);
    lv_label_set_text(lbl, "update");
    lv_obj_align(btn_aht, LV_ALIGN_CENTER, 50, 30);
    /*按键事件*/
    lv_obj_add_event_cb(btn, btn_cb, LV_EVENT_CLICKED, disp);
    lv_obj_add_event_cb(btn_aht, btn_ath_cb, LV_EVENT_CLICKED, disp);
}
